package org.lzx.converter.file;

import java.io.File;
import java.util.Iterator;
import java.io.FileWriter;
import java.util.LinkedList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * 
 * @author swagner
 * @date 29.06.2008
 *
 */
public class CreateClassFile {
	
	private static final Log log = LogFactory.getLog(CreateClassFile.class);
	
	private static CreateClassFile instance;

	private CreateClassFile() {}

	public static synchronized CreateClassFile getInstance() {
		if (instance == null) {
			instance = new CreateClassFile();
		}
		return instance;
	}
	
	public void createConfFile(File confDir, LinkedList<String> classNames) {
		try {
			
			String workingDir = confDir.getAbsolutePath();
			
			File confFile = new File (workingDir + File.separatorChar + GenerateClassStructure.confDirName);
			
			if (confFile.exists()) {
				confFile.delete();
			}
			
			log.debug("OutPut File: "+confFile.getAbsolutePath());
			
			this.writeToFile(confFile, classNames);
			
		} catch (Exception err) {
			log.error("[createConfFile]",err);
		}
	}
	
	public void writeToFile(File confFile, LinkedList<String> classNames) {
		try {
			
			Document document = DocumentHelper.createDocument();
	        Element root = document.addElement( "root" );

	        for (Iterator<String> iter = classNames.iterator();iter.hasNext();) {
	        	Element author1 = root.addElement( "class" )
	        		.addElement("name")
	        		.addText(iter.next());
	        }

			
	        // lets write to a file
	        XMLWriter writer = new XMLWriter(
	            new FileWriter( confFile )
	        );
	        writer.write( document );
	        writer.close();


	        // Pretty print the document to System.out
	        OutputFormat format = OutputFormat.createPrettyPrint();
	        writer = new XMLWriter( System.out, format );
	        writer.write( document );

	        // Compact format to System.out
	        format = OutputFormat.createCompactFormat();
	        writer = new XMLWriter( System.out, format );
	        writer.write( document );

			
		} catch (Exception err) {
			log.error("[writeToFile]",err);
		}
	}

}
